package org.feng.controller;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.feng.cilent.AliSmsClient;
import org.feng.cilent.AsyncSmsClient;
import org.feng.cilent.MailClient;
import org.feng.constant.RedisConstant;
import org.feng.entity.pojo.User;
import org.feng.entity.query.LoginQuery;
import org.feng.entity.vo.CaptchaImageVO;
import org.feng.entity.vo.LoginVO;
import org.feng.enums.Response;
import org.feng.pojo.Result;
import org.feng.service.MenuService;
import org.feng.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author by feng
 * @des 验证相关
 * @date 2021/4/27 14:03
 */
@RestController
@RequestMapping("/system/auth")
@AllArgsConstructor
@Api(value = "验证相关", tags = "验证相关")
@Slf4j
public class AuthController {
    private final MenuService menuService;
    private final UserService userService;
    private final StringRedisTemplate redisTemplate;
    private AliSmsClient aliSmsClient;
    private AsyncSmsClient asyncSmsClient;
    private MailClient mailClient;

    /**
     * 获取图形验证码
     *
     * @return
     */
    @GetMapping("/captchaImage")
    @ApiOperation("获取图形验证码")
    public Result<CaptchaImageVO> captcha(HttpServletRequest request) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha();
        String verCode = specCaptcha.text().toLowerCase();
        String key = IdUtil.simpleUUID();
        CaptchaImageVO captchaImageVO = new CaptchaImageVO();
        captchaImageVO.setImg(specCaptcha.toBase64());
        captchaImageVO.setKey(key);
        redisTemplate.opsForValue().set(RedisConstant.CAPTCHA_IMAGE_PRE + key, verCode, 1, TimeUnit.MINUTES);
//        AliSendSmsRequest smsRequest = new AliSendSmsRequest();
//        smsRequest.setOutId("111111111111");
//        smsRequest.setPhoneNumbers("15612509687");
//        smsRequest.setTemplateParam(new HashMap<>());
//        smsRequest.setSignName("sss");
//        smsRequest.setTemplateCode("154233");
//        try {
//            aliSmsClient.sendSms(smsRequest);
//            aliSmsClient.asyncSendSms(smsRequest);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        MailMessageBody body = new MailMessageBody();
//        body.setContent("测试mail发送组件");
//        body.setTitle("一封测试邮件");
//        body.setFrom("15612509687@163.com");
//        body.setTo("754443793@qq.com");
//        try {
//            mailClient.sendEmail(body);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return Result.success(captchaImageVO);
    }

    /**
     * 登录
     *
     * @param loginQuery
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<LoginVO> login(@RequestBody @Validated LoginQuery loginQuery) {
        String vCode = redisTemplate.opsForValue().get(RedisConstant.CAPTCHA_IMAGE_PRE + loginQuery.getKey());
        if (StrUtil.isEmpty(vCode)) {
            return Result.error(Response.CODE_INVALID);
        }
        if (!vCode.equalsIgnoreCase(loginQuery.getCode())) {
            return Result.error(Response.CODE_VALIDATION_INVALID);
        }
        User user = userService.getUserByUsername(loginQuery.getUsername());
        if (SaBase64Util.encode(loginQuery.getPassword()).equals(user.getPassword())) {
            //账号密码正确
            StpUtil.login(user.getId());
            //缓存用户信息
            redisTemplate.opsForValue().set(RedisConstant.USER_INFO + user.getId(), JSON.toJSONString(user));
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            LoginVO loginVO = LoginVO.builder()
                    .token(tokenInfo.tokenValue)
                    .tokenName(tokenInfo.tokenName)
                    .build();
            return Result.success(loginVO);
        } else {
            //账号密码错误
            return Result.error(Response.USERNAME_PASSWORD_INVALID);
        }
    }

    /**
     * 获取按钮权限
     *
     * @return
     */
    @GetMapping("/getAuthButtons")
    @ApiOperation("获取按钮权限")
    public Result<HashMap<String, Boolean>> getAuthButtons() {
        return Result.success(menuService.getAuthButtons());
    }


}
